package com.supor.aiot.common.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.Lifecycle;

import com.airbnb.lottie.LottieAnimationView;
import com.supor.aiot.common.R;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import autodispose2.AutoDispose;
import autodispose2.AutoDisposeConverter;
import autodispose2.androidx.lifecycle.AndroidLifecycleScopeProvider;

/**
 * @author: zook
 * @date: 2021/10/14
 */
public class BaseMVVMEnhanceFragment<M extends AndroidViewModel, V extends ViewDataBinding>
        extends BaseMVVMFragment<M, V> {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return initBinding(inflater, container);
    }

    private View initBinding(LayoutInflater inflater, ViewGroup viewGroup) {
        Type superclass = getClass().getGenericSuperclass();
        Class<?> aClass = (Class<?>) ((ParameterizedType) superclass).getActualTypeArguments()[1];
        mBaseBinding = DataBindingUtil.inflate(inflater,
                R.layout.fragment_base,
                null, false);
        try {
            Method method = aClass.getDeclaredMethod("inflate", LayoutInflater.class,
                    ViewGroup.class, boolean.class);
            bindingView = (V) method.invoke(null, inflater, mBaseBinding.container, true);
            initEvent();
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return mBaseBinding.getRoot();
    }

    public <T> AutoDisposeConverter<T> bindDestoryAutoDispose() {
        return AutoDispose.autoDisposable(
                AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)
        );
    }

    /**
     * 此方法弃用 自动反射获取bidning
     *
     * @see BaseMVVMEnhanceActivity#setContentView(int)
     */
    @Deprecated
    @Override
    public int setContent() {
        return 0;
    }
}
